package com.dkm.orproject.dkmoa.action.jurisdiction;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaJurisdiction;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.jurisdiction.OaJurisdictionService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.ThreeVo;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName : JurisdictionAction  //类名
 * @Description : 权限Action  //描述
 * @Author : 石智诚  //作者
 * @Date: 2020-08-17 09:43  //时间
 */
@RestController
@RequestMapping("OaJurisdictionAction")
public class OaJurisdictionAction {

    /**
     * 权限服务接口
     */
    @Resource
    OaJurisdictionService jurisdictionService;

    /**
     * 工具类
     */
    @Resource
    Tools tools;

    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 分页查询
     * @param jurisdiction 权限模型 用于条件查询
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 当前页数
     * @param limit 显示的行数
     * @return 权限集
     */
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(OaJurisdiction jurisdiction,
                                      String startTime,
                                      String endTime,
                                      Integer page,
                                      Integer limit,
                                      HttpServletRequest request){
        try{
            List<OaJurisdiction> dataDictionaries=jurisdictionService.findAll(jurisdiction,startTime,endTime,page,limit);
            Long rowCount=jurisdictionService.rowCount(jurisdiction,startTime,endTime);
            return Tools.maps(dataDictionaries,rowCount);
        }catch (Exception e){
            addErrorLog(request,"权限分页查询",e);
        }
        return null;

    }

    /**
     * 查询一级菜单
     * @param request 请求
     * @return 集合
     */
    @GetMapping("selectAll/{id}")
    @UserLoginToken
    public List<OaJurisdiction> selectAll(HttpServletRequest request,@PathVariable(value = "id",required = false) Long id){
        try{
            return jurisdictionService.selectAllOne(id);
        }catch (Exception e){
            addErrorLog(request,"权限查询上级菜单",e);
        }
        return null;
    }


    @GetMapping("findAlls")
    @UserLoginToken
    public List<ThreeVo> findAlls(HttpServletRequest request){
        try{
        List<OaJurisdiction> jurisdictions=jurisdictionService.selectAll(null);
        List<ThreeVo> threeVos=new ArrayList<>();
        for (OaJurisdiction jurisdiction : jurisdictions) {
            ThreeVo threeVo=new ThreeVo();
            // 菜单名称
            threeVo.setName(jurisdiction.getJurisdictionName());
            // 菜单id
            threeVo.setValue(jurisdiction.getPkJurisdictionId());
            if(jurisdiction.getJurisdictionSuperior()==0){
                threeVo.setSuperId(0L);
            }else{
                threeVo.setSuperId(jurisdiction.getJurisdictionSuperior());
            }
            threeVos.add(threeVo);
        }
            return tools.createTree(threeVos);
        }catch (Exception e){
            addErrorLog(request,"权限查询所有菜单",e);
        }
        return null;
    }

    @GetMapping("isExist/{keyword}")
    @UserLoginToken
    public Integer isExist(@PathVariable("keyword") String keyword, HttpServletRequest request){
        try{
        return jurisdictionService.isExist(keyword);
    }catch (Exception e){
        addErrorLog(request,"权限代码查重",e);
    }
        return null;
    }

    /**
     * id查询
     * @param id 权限主键
     * @return 权限模型
     */
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaJurisdiction findById(@PathVariable("id") Long id, HttpServletRequest request){
        try{
            return jurisdictionService.findById(id);
        }catch (Exception e){
            addErrorLog(request,"权限id查询",e);
        }
        return null;
    }

    @UserLoginToken
    @GetMapping("findByIds/{roleId}")
    public List<ThreeVo> findByIds(@PathVariable("roleId") Long id, HttpServletRequest request){
        try{
            return jurisdictionService.findByIds(id);
        }catch (Exception e){
            addErrorLog(request,"权限id查询",e);
        }
        return null;
    }

    /**
     * 关键字查询 主要用于下拉框查询
     * @param key 权限关键字
     * @return 权限集
     */
    @UserLoginToken
    @GetMapping("findKeyword/{key}")
    public List<OaJurisdiction> findKeyword(@PathVariable("key") String key,HttpServletRequest request){
        try{
            return jurisdictionService.findKeyword(key);
        }catch (Exception e){
            addErrorLog(request,"权限关键字查询",e);
        }
        return null;
    }

    /**
     * 查询报错日志新增
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(e.getLocalizedMessage());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }

    /**
     * 新增或修改
     * @param jurisdiction 权限模型
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("addOrUpdate")
    public Map<String,Object> addOrUpdate(OaJurisdiction jurisdiction, HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(jurisdiction)){
            return tools.rowMap(map,0,null);
        }
        try{
            if(jurisdiction.getPkJurisdictionId() !=null && jurisdiction.getPkJurisdictionId()>0){
                row=jurisdictionService.update(jurisdiction,personnel.getPersonnelName());
                log.setLogTitle("权限修改");
            }else{
                row=jurisdictionService.add(jurisdiction,personnel.getPersonnelName());
                log.setLogTitle("权限新增");
            }
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(jurisdiction).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            log.setLogTitle("权限操作");
            log.setLogType("0");
            log.setLogBody(e.getLocalizedMessage());
            tools.errorMap(map,log);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 权限id集
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String,Object> deleteAll(@RequestParam(value = "ids[]",required = false) Long[] ids,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            List<Long> list= Arrays.asList(ids);
            List<OaJurisdiction> jurisdictions=jurisdictionService.selectAll(list);
            row=jurisdictionService.deleteAll(list);
            log.setLogTitle("权限批量删除");
            log.setLogBody(JSON.toJSON(jurisdictions).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            log.setLogTitle("权限批量删除");
            log.setLogBody(e.getLocalizedMessage());
            log.setLogType("0");
            tools.errorMap(map,log);
        }
        return map;
    }

    /**
     * id删除
     * @param id 权限id
     * @param request 服务器请求
     * @return 影响的行数
     */
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable(value = "id",required = false)Long id,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            OaJurisdiction jurisdiction=jurisdictionService.findById(id);
            row=jurisdictionService.deleteById(id);
            log.setLogTitle("权限删除");
            log.setLogBody(JSON.toJSON(jurisdiction).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            log.setLogBody(e.getLocalizedMessage());
            log.setLogTitle("权限删除");
            log.setLogType("0");
            tools.errorMap(map,log);
        }
        return map;
    }

    /**
     * 简化代码
     * @param request 请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }
}
